package function;

import java.util.ArrayList;

public class ADD extends Function {

	ArrayList<Function> functions;

	public ArrayList<Function> getFunctions() {
		return functions;
	}

	public ADD(ArrayList<Function> f) {
		functions = new ArrayList<Function>();
		for (int i = 0; i < f.size(); i++) {
			if (!(f.get(i) instanceof Constant && ((Constant) f.get(i))
					.getConstant() == 0))
				this.functions.add(f.get(i));
		}
		if (this.functions.size() == 0)
			this.functions.add(new Constant(0));
	}

	public ADD(Function f1, Function f2) {
		functions = new ArrayList<Function>();
		if (!(f1 instanceof Constant && ((Constant) f1).getConstant() == 0))
			functions.add(f1);
		if (!(f2 instanceof Constant && ((Constant) f2).getConstant() == 0))
			functions.add(f2);
		if (functions.size() == 0)
			functions.add(new Constant(0));
	}

	public double evaluate(double x) {
		double sum = 0;
		for (int i = 0; i < functions.size(); i++)
			sum += functions.get(i).evaluate(x);
		return sum;
	}

	public Function differentiate() {
		ArrayList<Function> result = new ArrayList<Function>();
		for (int i = 0; i < functions.size(); i++) {
			if (!(functions.get(i) instanceof Constant))
				result.add(functions.get(i).differentiate());
		}
		if (result.size() == 0)
			result.add(new Constant(0));
		return new ADD(result);
	}

	public String toString() {
		String s = "(";
		for (int i = 0; i < functions.size() - 1; i++)
			s += functions.get(i).toString() + " + ";
		s += functions.get(functions.size() - 1).toString() + ")";
		return s;
	}
}
